package net.maku.security.service;

import cn.hutool.core.bean.BeanUtil;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import lombok.AllArgsConstructor;
import lombok.extern.slf4j.Slf4j;
import net.maku.framework.security.user.UserDetail;
import net.maku.member.dao.MemberUserDao;
import net.maku.member.entity.MemberUserEntity;
import net.maku.system.convert.SysUserConvert;
import net.maku.system.dao.SysOrgDao;
import net.maku.system.entity.SysOrgEntity;
import net.maku.system.service.SysUserDetailsService;
import org.springframework.security.core.userdetails.UserDetails;
import org.springframework.security.core.userdetails.UserDetailsService;
import org.springframework.security.core.userdetails.UsernameNotFoundException;
import org.springframework.stereotype.Service;

/**
 * 账号登录 UserDetailsService
 *
 * @author 阿沐 babamu@126.com
 * <a href="https://maku.net">MAKU</a>
 */
@Service
@AllArgsConstructor
@Slf4j
public class UserDetailsServiceImpl implements UserDetailsService {
    private final SysUserDetailsService sysUserDetailsService;
    private final MemberUserDao memberUserDao;

    private final SysOrgDao sysOrgDao;

    @Override
    public UserDetails loadUserByUsername(String username) throws UsernameNotFoundException {
        MemberUserEntity memberUserEntity = memberUserDao.selectOne(new LambdaQueryWrapper<MemberUserEntity>().eq(MemberUserEntity::getMobile, username));
        if (memberUserEntity == null) {
            log.error("用户名或密码错误：username={}",username);
            throw new UsernameNotFoundException("用户名或密码错误");
        }
        UserDetail userDetail = BeanUtil.copyProperties(memberUserEntity, UserDetail.class);
        SysOrgEntity sysOrgEntity = sysOrgDao.selectById(memberUserEntity.getOrgId());
        userDetail.setOrgName(sysOrgEntity.getUnionAbbreviation());
        return sysUserDetailsService.getUserDetails(userDetail);
    }

}
